<?php

namespace app\videos\model;

use think\Model;

class VideosType extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'mac_type';

    // 设置当前模型的数据库连接
    protected $connection = [];

    public function initialize()
    {
        parent::initialize();
        $this->connection = config('cms.db');
        if (!isset($this->modelKey) || empty($this->modelKey) || cache('modelKey') != $this->modelKey) {
            exit(json_encode(['msg' => '非法操作！', 'code' => 711]));
        }
    }

    /**
     * 核心函数, 将列表数据转化树形结构
     * 使用前提必须是先有父后有子, 即儿子的id必须小于父亲id
     * 列表数据必须安装id从小到大排序
     * @param $lists 原始列表数据
     * @param string $childKey 字段名
     * @return array 返回树形数据
     */
    public function listToTree($childKey = '_c', $is_super = false)
    {
        $res = cache('listToTree' . request()->module());
        if ($res) {
            return $res;
        }
        $map = [];
        $map[] = ['type_mid', 'eq', 1];
        if (!$is_super) {
            $map[] = ['type_status', 'eq', 1];
        }
        $lists = $this->field('type_id,type_mid,type_status,type_pid,type_name')->where($map)->order('type_sort asc')->select();
        if (!$lists) {
            return false;
        }
        if (count($lists) <= 0) {
            return [];
        }
        $lists = $lists->toArray();

        $res = $this->make_tree($lists, $childKey);

        $res = array_values($res);
        foreach ($res as $k => $v) {
            if (isset($v['_c']) && !empty($v['_c'])) {
                array_unshift($res[$k]['_c'], [
                    'type_id' => '全部',
                    'type_mid' => '全部',
                    'type_status' => '全部',
                    'type_name' => '全部',
                ]);
            }
        }
        cache('listToTree' . request()->module(), $res, 600);
        return $res;
    }

    //生成无限极分类树
    public function make_tree($arr, $childKey = '_c')
    {
        $refer = array();
        $tree = array();
        foreach ($arr as $k => $v) {
            $refer[$v['type_id']] = &$arr[$k]; //创建主键的数组引用
        }
        foreach ($arr as $k => $v) {
            $pid = $v['type_pid'];  //获取当前分类的父级id
            if ($pid == 0) {
                $tree[] = &$arr[$k];  //顶级栏目
            } else {
                if (isset($refer[$pid])) {
                    $refer[$pid][$childKey][] = &$arr[$k]; //如果存在父级栏目，则添加进父级栏目的子栏目数组中
                }
            }
        }
        return $tree;
    }
}
